package com.wanhong.springboot.ssm.framework.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author w_yu
 * @date 2020/11/26 15:10
 * @desc
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 设置缓存
     *
     * @param key
     * @param obj
     */
    public void set(String key, String obj) {
        redisTemplate.opsForValue().set(key, obj);
    }

    /**
     * 设置缓存，并设置过期时间
     *
     * @param key
     * @param obj
     * @param seconds TimeUnit.SECONDS默认为seconds
     */
    public void set(String key, String obj, Long seconds) {
        redisTemplate.opsForValue().set(key, obj, seconds, TimeUnit.SECONDS);
    }

    /**
     * 根据key获取
     *
     * @param key
     * @return
     */
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 通过key自增，自增因子为1
     * @param key
     * @return
     */
    public Long increment(String key) {
        return redisTemplate.opsForValue().increment(key, 1L);
    }

    /**
     * 删除
     * @param key
     */
    public void delete(String key){
        redisTemplate.delete(key);
    }
}
